package com.cwh.taskcenter.domain.engine.rule.function;

import com.alibaba.qlexpress4.runtime.Parameters;
import com.alibaba.qlexpress4.runtime.QContext;
import com.alibaba.qlexpress4.runtime.Value;
import com.alibaba.qlexpress4.runtime.function.CustomFunction;
import com.cwh.taskcenter.domain.engine.rule.context.AbstractContext;
import com.cwh.taskcenter.domain.task.gateway.UserTaskRecordGateWay;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;

import java.time.LocalDate;
import java.util.Collections;
import java.util.List;

/**
 * 连续签到
 * @author cwh
 */
@Slf4j
@QLExpressFunction("ContinuousSignIn")
public class ContinuousSignInFunction implements CustomFunction {

    @Autowired
    private UserTaskRecordGateWay userTaskRecordGateWay;


    @Override
    public Object call(QContext qContext, Parameters parameters) throws Throwable {
        String eventType = "signIn";
        AbstractContext context = (AbstractContext)qContext.attachment().get("context");
        if (context == null) {
            return false;
        }
        log.info("context is {}",context.getUserId());

        Long taskId = context.getTaskId();
        Long userId = context.getUserId();
        Value value = parameters.get(0);
        if (value == null) {
            return false;
        }

        List<LocalDate> signInDates = userTaskRecordGateWay.getUserSignInDates(eventType, userId, taskId);
        if (CollectionUtils.isEmpty(signInDates)) {
            return false;
        }

        // 按日期降序排序
        signInDates.sort(Collections.reverseOrder());
        int continuousDays = calculateContinuousDays(signInDates) + 1;
        log.info("连续签到天数: {}", continuousDays);

        return continuousDays > (Integer) value.get();
    }

    /**
     * 计算连续签到天数
     */
    /**
     * 计算连续签到天数
     */
    private int calculateContinuousDays(List<LocalDate> dates) {
        if (dates.isEmpty()) {
            return 0;
        }

        // 检查今天是否签到
        LocalDate today = LocalDate.now();
        if (!dates.contains(today)) {
            // 如果今天没有签到，则从昨天开始计算
            LocalDate yesterday = today.minusDays(1);
            if (!dates.contains(yesterday)) {
                // 如果昨天也没有签到，则连续签到天数为0
                return 0;
            }
        }

        // 计算连续签到天数
        int continuousDays = 1;
        LocalDate currentDate = dates.get(0);

        for (int i = 1; i < dates.size(); i++) {
            LocalDate nextDate = dates.get(i);
            if (currentDate.minusDays(1).equals(nextDate)) {
                continuousDays++;
                currentDate = nextDate;
            } else {
                // 发现不连续，终止计算
                break;
            }
        }

        return continuousDays;
    }


}
